package com.zlx.guguanjia.service.impl;

import com.alibaba.excel.EasyExcel;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zlx.guguanjia.entity.SysArea;
import com.zlx.guguanjia.listener.SysAreaListener;
import com.zlx.guguanjia.mapper.SysAreaMapper;
import com.zlx.guguanjia.service.SysAreaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author 周罗校
 * @Description
 * @ClassName SysAreaServiceImpl
 * @date 2020.10.30 13:35:11
 * 该版权归周罗校所有，最终解释权以官方为准
 */

@Service
@Transactional
public class SysAreaServiceImpl extends BaseServiceImpl<SysArea,Long> implements SysAreaService {
    @Autowired
    private SysAreaMapper mapper;

    /***
     * @Author 周罗校
     * @Description
     * @Param [start, pageSize, map:{sid,name}]
     * @return com.github.pagehelper.PageInfo<com.zlx.guguanjia.entity.SysArea>
     * @Date 2020.10.30 13:37:56
     **/
    @Override
    public PageInfo<SysArea> selectPage(int start, int pageSize, Map<String, Object> map) {
        PageHelper.startPage(start,pageSize);
        return new PageInfo<>(mapper.selectPage(map));
    }
    @Override
    public List<SysArea> selectAll(){
        Map<String, Object> map = new HashMap<>();
        return mapper.selectPage(map);
    }

    @Override
    public SysArea selectById(Long id) {
        return mapper.selectById(id);
    }

    String oldParentIds = null;
    @Override
    public int updateByPrimaryKeySelective(SysArea area){
        int result = 0;
        if (!StringUtils.isEmpty(area)&&!StringUtils.isEmpty(area.getParentId())){
            oldParentIds = area.getParentIds();
            SysArea parent = mapper.selectByPrimaryKey(area.getParentId());
            area.setParentIds(parent.getParentIds()+parent.getId()+",");
            mapper.updateByPrimaryKeySelective(area);
        }
        if (!oldParentIds.equals(area.getParentIds())){
            mapper.updateByParentIds(oldParentIds+area.getId()+",",
                    area.getParentIds()+area.getId()+",",area.getId());
        }
        return  result;
    }

    @Override
    public void upload(InputStream is) {
        //文件的上传和通过excel的
        EasyExcel.read(is,SysArea.class,new SysAreaListener(mapper)).
                sheet().doRead();
    }

    @Override
    public void download(OutputStream os) {
        EasyExcel.write(os, SysArea.class).sheet().doWrite(mapper.selectAll());
    }

}
